import { Request, Response, NextFunction } from 'express'
import fs from 'fs'
import path from 'path'

import { getFormattedDate, getFormattedDateTime } from '../utils/date'

const loggerMiddleWare = (req: Request, res: Response, next: NextFunction) => {

  const { method, url, ip } = req
  // 获取当天的日志文件路径
  const logPath = path.join(__dirname, "../../logs", `${getFormattedDate()}.txt`)
  const logEntry = `时间: ${getFormattedDateTime()} - ip: ${ip} - 请求方式: ${method} - 请求地址: ${url}\n`
  console.log(logEntry)
  fs.appendFile(logPath, logEntry, (error) => {
    if (error) {
      console.error('Failed to write log:', error)
    }
  })

  next()
}

export default loggerMiddleWare